package com.restphp.java.utils.http;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * CVSResponseUtils.
 *
 * @author zj.
 *         Created on 2018/7/26 0026.
 */
public class CVSResponseUtils {
    /**
     * CVS输出(gbk).
     * @param response
     * @param headers
     * @param dataList
     * @param fileName
     */
    public static void writeResponse(HttpServletResponse response, Map<String, String> headers,
                                     List<Map> dataList, String fileName) {
        writeResponse(response, headers, dataList, fileName, "gbk");
    }
    /**
     * CVS输出.
     * @param response
     * @param headers
     * @param dataList
     * @param fileName
     * @param charset
     */
    public static void writeResponse(HttpServletResponse response, Map<String, String> headers,
                                     List<Map> dataList, String fileName, String charset) {
        response.setContentType("application/ms-excel;charset=" + charset);
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".csv");

        StringBuilder title = new StringBuilder();

        //表头
        int i=0;
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            if (i>0) {
                title.append(",");
            }
            title.append("\"").append(headers.get(entry.getKey())).append("\"");
            i++;
        }

        OutputStream out;
        try {
            //表头输出
            out = response.getOutputStream();
            out.write(title.toString().getBytes(charset));

            //数据
            for (Map data : dataList) {
                StringBuilder dataOutBuffer = new StringBuilder("\n");
                int j = 0;
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String key = entry.getKey();
                    String info = data.containsKey(key) ? String.valueOf(data.get(key)) : "";
                    if (j > 0) {
                        dataOutBuffer.append(",");
                    }
                    dataOutBuffer.append("\"").append(info).append("\"");
                    j++;
                }
                out.write(dataOutBuffer.toString().getBytes(charset));
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
